package com.dsc.shoppcar.servlet;

import com.dsc.shoppcar.dao.DataMoniDao;
import com.dsc.shoppcar.pojo.Goods;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author: Du Shun Chang
 * @title: CartServlet
 * @date: 2022/4/14 8:39
 * @description: TODO
 * @version：1.0
 */
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 全部商品
        List<Goods> data = DataMoniDao.getData();
        // 响应设置
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        // 获取加入购物车商品的信息
        String id = request.getParameter("id");
        Goods good = new Goods(id,"",0.0,"");

        for(Goods g : data) {
            if(g.compareTo(good) == 1) {
                good = g ;
                break;
            }
        }

        // 将商品信息加入cookies
        Cookie cookie = new Cookie("cookie_order_" + good.getId() , good.getId() + "");
        // 设置cookie的生命周期：
        // 如果此处不写 ， 将写入浏览器临时cookie中，无法存在客户端本地cookie文件
        cookie.setMaxAge(36000);
        response.addCookie(cookie);

        // 完成了cookie操作，还要进行持久化操作，在学习了jdbc之后加入本功能
        // 持久化操作包括：更新购物车信息： 包括 商品总价、商品数量、详细信息等等...
        /* ... 此处省略代码30000行... */

        // 重定向到当前页
        response.sendRedirect(this.getServletContext().getContextPath() + "/index");
        // 请求转发
//		request.getRequestDispatcher("/index").forward(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);

    }
}
